<?php

namespace app\service;

use app\exception\CommonException;
use app\model\Config;
use app\model\Market;
use app\model\Member;
use think\exception\ValidateException;

class MemberService extends BaseService
{


    protected function setModel(): string
    {
        return Member::class;
    }

    public function login($email, $passwd, $remember)
    {
        $member = $this->getOne(["email" => $email], "id,status,passwd");
        if (empty($member)) {
            throw new ValidateException("账户或密码错误");
        }
        if ($member->status == 2) {
            throw new ValidateException("账户已经被冻结");
        }
        if (!password_verify($passwd, $member->passwd)) {
            throw new ValidateException("账户或密码错误");
        }
        session("mid", $member->id);
        if ($remember) {
            cookie("email", h_encrypt($email));
        }
    }


    public function getList($where = [], $field = "*", array $with = [], array $hasWhere = [])
    {
        $page = request()->post("page", 1);
        $pageSize = request()->post("limit", 10);
        $offset = ($page - 1) * $pageSize;
        $list = $this->getModel()->where($where)->field($field)->order($this->getOrder())->limit($offset, $pageSize)->select()->toArray();
        foreach ($list as $key => $v) {
            $tree = $v["tree"];
            if (empty($tree)) {
                continue;
            }
            $pids = explode("|", $tree);
            if (count($pids) > 3) {
                $pids = array_chunk($pids, 3);
                $pids = $pids[0];
            }
            if (!empty($pids)) {
                $sons = $this->column(["id" => $pids], "id,email", 'id');
                foreach ($pids as $k => $pid) {
                    $list[$key]["son"][$k] = $sons[$pid];
                }
            }
        }
        $total = $this->getModel()->where($where)->count();;
        return ["rows" => [
            "total" => $total,
            "list" => $list,
        ]];
    }

    /**
     * 返回三级代理
     * @param $mid
     * @return array|false]
     */
    public function getAgentMapByMid($mid): bool|array
    {
        $global = config("global");
        $firstRebate = floatval($global["FIRST_REBATE"]);
        $secondRebate = floatval($global["SECOND_REBATE"]);
        $thirdRebate = floatval($global["THIRD_REBATE"]);
        if ($firstRebate > 100 || $secondRebate > 100 || $thirdRebate > 100 || $firstRebate < 0 || $secondRebate < 0 || $thirdRebate < 0) {
            throw new CommonException("返佣比例配置有误，请仔细检查");
        }
        $agents = $this->get($mid, ["tree"]);
        if (!$agents->tree) {
            return false;
        }
        $pids = explode("|", $agents->tree);
        $pids = array_slice($pids, 0, 3);
        $arr = $this->column(["id" => $pids], "id,realname", 'id');
        if (!empty($pids[0])) {
            $arr[$pids[0]]["percent"] = $firstRebate;
        }
        if (!empty($pids[1])) {
            $arr[$pids[1]]["percent"] = $secondRebate;
        }
        if (!empty($pids[2])) {
            $arr[$pids[2]]["percent"] = $thirdRebate;
        }
        return $arr;
    }

    public function getLevelCount($level): int
    {
        $uid = app()->request->uid;
        $params["uid"] = $uid;
        switch ($level) {
            case 1:
                $sql = "SUBSTRING_INDEX(tree, '|', 1) = :uid";
                break;
            case 2:
                $sql = "  SUBSTRING_INDEX(SUBSTRING_INDEX(tree, '|', 2), '|', -1) = :uid AND (LENGTH(tree) - LENGTH(REPLACE(tree, '|', ''))) >= :level";
                $params["level"] = $level-1;
                break;
            case 3:
                $sql = "  SUBSTRING_INDEX(SUBSTRING_INDEX(tree, '|', 3), '|', -1) = :uid AND (LENGTH(tree) - LENGTH(REPLACE(tree, '|', ''))) >= :level";
                $params["level"] = $level-1;
                break;
            default:
                throw new ValidateException("只支持3级查询");

        }
        return $this->getWhereRawCount($sql, $params);
    }

    public function getLevelList($level, $field = "*")
    {
        $uid = app()->request->uid;
        $params["uid"] = $uid;
        switch ($level) {
            case 1:
                $sql = "SUBSTRING_INDEX(tree, '|', 1) = :uid";
                break;
            case 2:
                $sql = "  SUBSTRING_INDEX(SUBSTRING_INDEX(tree, '|', 2), '|', -1) = :uid AND (LENGTH(tree) - LENGTH(REPLACE(tree, '|', ''))) >= :level";
                $params["level"] = $level-1;
                break;
            case 3:
                $sql = "  SUBSTRING_INDEX(SUBSTRING_INDEX(tree, '|', 3), '|', -1) = :uid AND (LENGTH(tree) - LENGTH(REPLACE(tree, '|', ''))) >= :level";
                $params["level"] = $level-1;
                break;
            default:
                throw new ValidateException("只支持3级查询");
        }
        $list = $this->getWhereRawList($sql, $params, $field);
        return $list;
    }

    public function getLevelSum($level):array
    {
        $list = $this->getLevelList($level,"id");
        $uids = array_column($list,"id");
        if (empty($uids)) {
            return [];
        }
        $memberCoinService = app()->make(MemberCoinService::class);
        $list = $memberCoinService->getAll(["member_id" => $uids], "member_id,coin_id,account_amount");
        $data = [];
        foreach ($list as $pay) {
            $data[$pay->member_id][] = ["coin_id" => $pay->coin_id, "account_amount" =>$pay->account_amount];
        }
        $marketService = app()->make(MarketService::class);
        $assets = [];
        foreach ($data as $uid => $wallets) {
            $sum = 0;
            foreach ($wallets as $wallet) {
                $sum += $marketService->getClosePriceByUsdt($wallet["coin_id"], $wallet["account_amount"]);
            }
            $assets[$uid] = $sum;
        }
        return $assets;
    }

}